import QtQuick 1.0
//import ShellInvoker 1.0
import "../../../common/lib/kdeadmouseutils-build-desktop"

Item {
    id:mainCptModel
    property alias model: movieBuildModel
    property int lastBuilt : 0;
    property bool working : false;
    
    function globalEnrich(currentIdx){
      
	if(lastBuilt-currentIdx>5){
	  //console.log('no work todo!! lastBuilt:'+lastBuilt+', currentIdx:'+currentIdx+', enrichCount:'+model.count+', tmpCount:'+tmpModel.count);
	  return;
	}
	
	if(working){
	  //console.log('working yet!!');
	  return;
	}
	
	working=true; var nbItems=0;
        while(lastBuilt<tmpModel.count && nbItems++<5){// && lastBuilt<maxNumItem){
	  //console.log('enrich the:'+ lastBuilt);
	  var m = tmpModel.get(lastBuilt++);
	  enrichItem(m);
	}
	//console.log('enrich FIN:'+ lastBuilt);
	working=false;
    }
    
    
    ListModel {
      id: movieBuildModel
    }
    
    ListModel {
	  id : tmpModel
    }
    
    function searchGoogleImg(query){
      //https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%22Pop%20et%20le%20nouveau%20monde%22
    }
    function searchYoutubeTrailer(query){
      //https://gdata.youtube.com/feeds/api/videos?q=%22Extracted%22&v=2&alt=json&category=Film&hl=fr-FR&lang=fr&fields=entry(title,media:group(media:description,yt:videoid))
    }
    function enrichItem(model){
      if(!model.idTMD){
	console.log('==================>no id thesmoviedb for <' + model.title+'>');
	addRichItem(model,{title:model.title})	  
	return;
      }
      var urlJson='http://api.themoviedb.org/3/movie/' + model.idTMD + '?api_key='+setting.value('apiKey')+'&language=FR&append_to_response=trailers,images,casts';
      
      var xhr = new XMLHttpRequest();
      
      xhr.onreadystatechange = function()
      {
	  /*if (xhr.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
                         console.log("Headers -->");
                         console.log(xhr.getAllResponseHeaders ());
                         console.log("Last modified -->");
                         console.log(xhr.getResponseHeader ("Last-Modified"));

          }else */
	    if ( xhr.readyState == xhr.DONE)
	  {
	    if ( xhr.status == 200){
		  var oJson = eval('(' + xhr.responseText + ')');
		  var shorty = {};
		  var direct = "";
		  var actors = "";
		  var imgPref= "http://cf2.imgobject.com/t/p/original";
		  var allP=[{url:imgPref+oJson.backdrop_path}];
		  var trailer;
		  //console.log('Parsing response for : '+model.idTMD);
		  try{
		    if(oJson.casts && oJson.casts.crew){ 
		      direct = oJson.casts.crew[0].name;
		    }
		    if(oJson.casts && oJson.casts.cast){
		      var allCasts = oJson.casts.cast;
		      for(var i=0;i<allCasts.length;i++){
			actors +=' , '+allCasts[i].name;
		      }
		    }
		    if(oJson.images && oJson.images.posters){
		      var allImg = oJson.images.posters;
		      for(var i=0;i<allImg.length;i++){
			allP.push({url:imgPref+allImg[i].file_path});
			//console.log('shorty photo===>:'+allImg[i].file_path);
		      }
		    }
		    //ajout des acteurs...
		    if(oJson.casts && oJson.casts.cast){
		      allImg = oJson.casts.cast;
		      for(var i=0;i<allImg.length;i++){
			if(allImg[i].profile_path != null){
			  allP.push({url:imgPref+allImg[i].profile_path});
			}
		      }
		    }  
		    
		    //recherche du trailer, le premier d'une liste
		    if(oJson.trailers && oJson.trailers.youtube&& oJson.trailers.youtube.length){
			trailer = oJson.trailers.youtube[0].source
		    }
		    
		  }catch(e){
		    console.log(e);
		    console.log("===============parsing error:"+model.title);
		  }
		  
		  
		  try{
		  shorty = {
		    id:oJson.id,
		    title:oJson.title,
		    tagline:oJson.tagline,
		    productionYear:oJson.release_date,
		    duree:oJson.runtime,
		    synopsisShort:oJson.overview,
		    synopsis:oJson.overview,
		    directors:direct,
		    actors:actors,
		    poster:imgPref+oJson.poster_path,
		    photo:allP,
		    trailerUrlYT:trailer
		  };
		  //console.log('shorty==>' + JSON.stringify(shorty));
		  }catch(e){
		    console.log(e);
		    console.log(model.idAllocine);
		    console.log('shorty==>' + JSON.stringify(shorty));
		  }
		  
		  //console.log('shorty photo 0 :'+shorty.photo[0]);
		  //console.log('shorty photo 1 :'+shorty.photo[1]);
		  addRichItem(model,shorty)
	      }else{
		console.log('url:'+urlJson);
		console.log('===========status=>' + xhr.status);
	      }
	  }
      }
      xhr.open("GET",urlJson,true);
      xhr.setRequestHeader("Accept","application/json"); 
      xhr.send();
      
    }
    
    function addRichItem(origin,obj){
	  obj.url=origin.url;
	  obj.titleM=origin.title;
	  obj.annee=origin.annee;
	  obj.genre = origin.genre ;
	  if(!obj.poster || obj.poster==''){
	    obj.poster='images/noposter.png';
	  }
	  movieBuildModel.append(obj);
	  //console.log('adding==>' + obj.title + ', pict:'+obj.photo  );
    }
    
   /* XmlListModel {
	property string movieIdAdding
	property variant itemAdding
	property int numTrait : 0
	id: movieXmlModel
	source: 
	query: "/movie"
	namespaceDeclarations: "declare default element namespace 'http://www.allocine.net/v6/ns/';"
	XmlRole { name: "id" ; query: "@code/string()" ; isKey : true}
	XmlRole { name: "title"; query: "title/string()" }
	XmlRole { name: "productionYear"; query: "productionYear/string()" }
	XmlRole { name: "duree"; query: "runtime/string()" }
	XmlRole { name: "synopsisShort"; query: "synopsisShort/string()" }
	XmlRole { name: "synopsis"; query: "synopsis/string()" }
	XmlRole { name: "directors"; query: "castingShort/directors/string()" }
	XmlRole { name: "actors"; query: "castingShort/actors/string()" }
	XmlRole { name: "poster"; query: "poster/@href/string()" }
	XmlRole { name: "trailerCode"; query: "trailer/@code/string()" }
	XmlRole { name: "photo1"; query: "mediaList/media[1]/thumbnail/@href/string()" }
	XmlRole { name: "photo2"; query: "mediaList/media[2]/thumbnail/@href/string()" }
	XmlRole { name: "photo3"; query: "mediaList/media[3]/thumbnail/@href/string()" }
	XmlRole { name: "photo4"; query: "mediaList/media[4]/thumbnail/@href/string()" }
	XmlRole { name: "photo5"; query: "mediaList/media[5]/thumbnail/@href/string()" }
	XmlRole { name: "photo6"; query: "mediaList/media[6]/thumbnail/@href/string()" }
	onStatusChanged: {
	      if (status == XmlListModel.Ready){
		  //pour une raison que j ignore, le reload ne marche pas !!!
		  if(count==1){
		    var obj = get(0);
		    addObj(obj);
		  }
		  addMovie();
	      }
	}
	
	
	
	
	function addMovie(){
	  itemAdding = tmpModel.get(numTrait);
	  numTrait++;
	  console.log('numTrait==>' + numTrait +'length:' + tmpModel.count);
	  if(mainCptModel.maxNumItem>0 && numTrait>mainCptModel.maxNumItem){
	    return;
	  }
	  if(!itemAdding){
	    return;
	  }
	  if(!itemAdding.idAllocine){
	    var obj = {
	       poster:'images/noposter.png'
	      ,synopsisShort:'inconnu'
	      ,title:itemAdding.title
	    };
	    addObj(obj);
	    return addMovie();
	  }
	  movieIdAdding=itemAdding.idAllocine;
	  return;
	}
    }*/
    
    
    
    ShellInvoker {
	id:magikFileTube
	waitFor:'start'
	onFinished : {
	  mainCptModel.globalEnrich(5);
	}
	onOutputLineChanged : {
	    var sl = "("+ magikFileTube.outputLine +")" ;
	    try{
	      var l = eval(sl);
	      tmpModel.append(l);
	      //console.log(l.title + '...');
	    }catch(err){
	      console.log(err);
	      console.log("eval##"  + sl+"##");
	    }
	}
    }
   
    QmlSetting{
      id:setting
      appName:'allocine'
    }
    
    Component.onCompleted: {
      magikFileTube.shellAction('/socMDC/KdeadMouse/apps/allocine/bin/magikData.sh',[setting.value('magikUrl')]);
    }  
   
        
}
 
